package com.aote.rs;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

/**
 * JSON service 调用隧道
 * 
 * @author lgy
 *
 */
@Path("tunnel")
@Component
public class Tunnel {
	static Logger log = Logger.getLogger(Tunnel.class);

	@GET
	@Produces("application/x-javascript")
	public String test(@QueryParam("callback") String callback) {
		return callback + "({\"hello\": \"Hello Tunnel\"})";
	}

	@POST
	@Path("/post")
	@Produces(MediaType.APPLICATION_JSON)
	public String postPost(String body)
	{
	    DefaultHttpClient httpclient = new DefaultHttpClient();
	    try {
			JSONObject jo = new JSONObject(body);
			HttpPost postRequest = new HttpPost(jo.getString("url"));
			postRequest.setEntity(new StringEntity(jo.getString("body"),  "UTF-8"));
			HttpResponse httpResponse = httpclient.execute(postRequest);
			if(httpResponse.getStatusLine().getStatusCode() != 200)
				throw new WebApplicationException(400);
			HttpEntity entity = httpResponse.getEntity();
			if(entity != null)
				return EntityUtils.toString(entity,"UTF8");
			else
				return "";
	    } catch (Exception e) {
	    	throw new WebApplicationException(400);
	    } finally {
	      httpclient.getConnectionManager().shutdown();
	    }
	}
	
	@POST()
	@Path("/get")
	@Produces(MediaType.APPLICATION_JSON)
	public String postGet(String url)
	{
	    DefaultHttpClient httpclient = new DefaultHttpClient();
	    try
	    {
	      HttpGet getRequest = new HttpGet(url);
	      HttpResponse httpResponse = httpclient.execute(getRequest);
          if(httpResponse.getStatusLine().getStatusCode() != 200)
			throw new WebApplicationException(400);
	      HttpEntity entity = httpResponse.getEntity();
	      if(entity != null)
	    	  return EntityUtils.toString(entity,"UTF8");
	      else
	    	  return "";

	    } catch (Exception e) {
	    	throw new WebApplicationException(400);
	    } finally {
	      httpclient.getConnectionManager().shutdown();
	    }
	}
	
}
